package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public void add(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);

        addressMapper.insert(address);
    }

    @Override
    public List<Address> findList() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        List<Address> addressList = addressMapper.selectList(wrapper);

        return addressList;
    }

    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);
        return address;
    }

    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void deleteById(List<Long> ids) {
        if (CollectionUtil.isNotEmpty(ids)){
            addressMapper.deleteBatchIds(ids);
        }
    }

    @Override
    public void setDefault(Address address) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        Address address1 = new Address();
        address1.setIsDefault(0);
        addressMapper.update(address1,wrapper);

        address.setIsDefault(1);
        addressMapper.updateById(address);
    }

    @Override
    public Address getDefault() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault,1);
        Address address = addressMapper.selectOne(wrapper);
        return address;
    }
}
